package at.fhooe.swa.client.domain;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.plaf.basic.BasicInternalFrameTitlePane.RestoreAction;

import at.fhooe.swa.client.util.Resources;

public class SensorRegister implements ISensorRegister
{
	Map<String, ISensor> registeredSensors = new HashMap<String, ISensor>();
	private String lastUpdateTime;
	
	private boolean checkProperties(Object... properties)
	{
		for (Object p : properties)
		{
			if (p == null)
				return false;
		}
		
		return true;
	}
	
	@Override
	public void addSensorByName(String name)
	{
		if (sensorAlreadyRegisterd(name))
			return;
		
		String sensorType = Resources.getSensorProperty(name + ".type");
		
		if (sensorType == null)
		{
			System.err.println("Sensor \"" + name + "\" not registered! Check the sensor properties file!");
			return;
		}
		
		ISensor sensorToAdd = null;
		
		switch (sensorType)
		{
			case "Double":
			{
				String displayLabel = Resources.getSensorProperty(name + ".label");
				String unit = Resources.getSensorProperty(name + ".unit");
				String minVal = Resources.getSensorProperty(name + ".minVal");
				String maxVal = Resources.getSensorProperty(name + ".maxVal");
				String initVal = Resources.getSensorProperty(name + ".initVal");
				
				if (checkProperties(displayLabel, unit, minVal, maxVal, initVal))
				{
					sensorToAdd = new DoubleSensor(
							name, 
							displayLabel, 
							unit, 
							Double.parseDouble(minVal), 
							Double.parseDouble(maxVal), 
							Double.parseDouble(initVal));
				}
				else
					System.err.println("The sensor \"" + name + "\" is not properly defined.");
				break;
			}
			case "Boolean":
			{
				String displayLabel = Resources.getSensorProperty(name + ".label");
				String unit = Resources.getSensorProperty(name + ".unit");
				if (checkProperties(displayLabel, unit))
				{
					sensorToAdd = new BooleanSensor(
							name, 
							displayLabel, 
							unit);
				}
				else
					System.err.println("The sensor \"" + name + "\" is not properly defined.");
				break;
			}
			default:
				break;
		}
		
		registeredSensors.put(name, sensorToAdd);
		
	}

	@Override
	public boolean sensorAlreadyRegisterd(String name)
	{
		return this.registeredSensors.get(name) != null;
	}

	@Override
	public Collection<ISensor> getRegisteredSensors()
	{
		return registeredSensors.values();
	}
	
	@Override
	public String getLastUpdateTime()
	{
		return lastUpdateTime;
	}
	
	@Override
	public void setLastUpdateTime(String dateTime)
	{
		this.lastUpdateTime = dateTime;
	}

	@Override
	public ISensor getSensor(String key)
	{
		return registeredSensors.get(key);
	}

}
